#!/usr/bin/env python2
# coding: utf-8 

# Copyright (C) 2020 mn

# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/.

proginf = "outfox 0.1, mar 2020 mn"
import curses as cur
import sys
import os

from sys import argv
from sys import stdin, stdout
from time import sleep
from os import popen

try: from sys import exit as quit
except: pass

def thee(k):
    try:
        cls(k)
    except KeyboardInterrupt:
        pass  
    while 1:
        try:
            m(k)
        except KeyboardInterrupt:
            break

def prints(k, p):
    try:
        k.addstr(str(p))    
    except:
        pass
    k.refresh()

def arrcurl(p):
    from urllib import urlopen
    x = str(urlopen(p).read())
    x = x.replace(chr(13) + chr(10), 
    chr(10)).replace(chr(13), chr(10)).split(chr(10))
    return x[:]

def arropen(p):
    x = open(p).read().replace(chr(13) + chr(10), chr(10)).replace(chr(13), 
    chr(10)).split(chr(10))
    return x[:]

def figarrshell(c):
    global figsysteme
    from os import popen as po
    try:
        figsysteme = 0
        sh = po(c)
        ps = sh.read().replace(chr(13) + chr(10), 
        chr(10)).replace(chr(13), chr(10)).split(chr(10))
        figsysteme = sh.close()
    except:
        print "error running arrshell command: " + chr(34) + str(c) + chr(34) 
        quit()
    return ps[:]

def printn(k, p):
    try:
        k.addstr(str(p) + chr(10))
    except:
        pass
    k.refresh()

def cls(k):
    k.clear()
    k.refresh()

def locate(k, h, v):
    try:
        k.addstr(h - 1, v - 1, "")
    except:
        pass

def right(p, s):
    return p[-s:]

def left(p, s):
    return p[:s]

def right(p, s):
    return p[-s:]

def back(p, s):
    if s < len(p):
        return p[:len(p) - s]
    else:
        return ""

def getkey(k):
    p = k.getch()
    try: p = chr(p)
    except: pass
    return p

def inc(p):
    return p + 1

def parsehref(p):
    if left(p.lower(), 3) == "<a ":
        if "href" in p.lower():
            return p
    return ""

def gopherparse(k, p):
    gps = ""
    freewiki = 0
    script = 0
    for each in p:
        buf = ""
        intag = 0
        tagbuf = ""
        for eaches in each:
            if eaches == "<" and intag == 0:
                intag = 1
            if intag == 0 and script < 1:
                buf += eaches
            else:
                tagbuf += eaches
            if right(buf, 5) == "[url]" and freewiki == 1:
                buf = back(buf, 5) + chr(10)
            if right(buf, 5) == "[lit]" and freewiki == 1:
                buf = back(buf, 5)
            if tagbuf.lower() == "<script" and script == 0:
                script = 1
            if eaches == ">" and intag == 1:
                intag = 0
                phref = parsehref(tagbuf)
                if phref > "": 
                    buf += chr(10) + phref + chr(32)
                if tagbuf.lower() in ("<br>", "<br/>", "</p>", "</div>", "</li>"):
                    buf += chr(10)
                if tagbuf.lower() == """<span id = "wiki">""" and freewiki == 0:
                    freewiki = 1
                if tagbuf.lower() == "</span>" and freewiki == 1:
                    freewiki = 0
                if tagbuf.lower() == "</script>" and script == 1:
                    script = 0
                tagbuf = ""
        gps += buf
        if freewiki == 1:
            gps += chr(10)
        #gps += "NEWLINE"
    return gps.split(chr(10))

def m(k):
    colours = {}
    cur.init_pair(inc(0), cur.COLOR_BLACK, cur.COLOR_BLACK)
    cur.init_pair(inc(1), cur.COLOR_BLACK, cur.COLOR_BLUE)
    cur.init_pair(inc(2), cur.COLOR_BLACK, cur.COLOR_GREEN)
    cur.init_pair(inc(3), cur.COLOR_BLACK, cur.COLOR_CYAN)
    cur.init_pair(inc(4), cur.COLOR_BLACK, cur.COLOR_RED)
    cur.init_pair(inc(5), cur.COLOR_BLACK, cur.COLOR_MAGENTA)
    cur.init_pair(inc(6), cur.COLOR_BLACK, cur.COLOR_YELLOW)
    cur.init_pair(inc(7), cur.COLOR_BLACK, cur.COLOR_WHITE)
    for each in range(8):
        colours[(each, 0)] = cur.color_pair(inc(each))
    locate(k, 2, 5)
    prints(k, unichr(9608))
    p = getkey(k)
    if p in ("q", "Q", chr(27)):
        prints(k, chr(10) + "quit now? ")
        gc = getkey(k)
        if gc != chr(27):
            prints(k, gc)
        if gc in ("y", "Y"):
            quit()
    sq = ""
    if p in ("f", "F"):
        outfile = open("outfox.txt", "w")
        p = "u"
    if p in ("s", "S"):
        allowed = "qazwsxedcrfvtgbyhnujmikolp ./;'- 1234567890 ="
        allowed += "QAZWSXEDCRFVTGBYHNUJMIKOLP ?: _|!@#$%^&*()~"
        prints(k, chr(10) + "search for: ")
        while 1:
            gc = getkey(k)
            if gc in allowed:
                prints(k, gc)
                sq += gc
            if gc in [chr(10), chr(13)]:
                sq = sq.strip()
                break
            if gc in [chr(27)]:
                sq = ""
                break
        if sq:
            p = "u"
    if p in ("u", "U"):
        url = ""
        try:
            filters = arropen(".outfoxfilter")
        except:
            filters = []
        try:
            rc = arropen(".outfoxrc")
        except:
            rc = []
        allowed = "qazwsxedcrfvtgbyhnujmikolp ./;'- 1234567890 ="
        allowed += "QAZWSXEDCRFVTGBYHNUJMIKOLP ?: _|!@#$%^&*()~"
        qn = 0
        for opts in argv[1:]:
            if "=" in opts:
                if opts.split("=")[0].lower() == "url":
                    url = "=".join(opts.split("=")[1:len(opts)])
                if opts.split("=")[0].lower() == "q":
                    qn = int(opts.split("=")[1])
        tag2spc = 0
        for opts in rc:
            if "=" in opts:
                if opts.split("=")[0].lower() == "tag2spc":
                    tag2spc = int(opts.split("=")[1])
        if url == "":
            prints(k, chr(10) + "goto url: ")
            while 1:
                gc = getkey(k)
                if gc in allowed:
                    prints(k, gc)
                    url += gc
                if gc in [chr(10), chr(13)]:
                    url = url.strip()
                    break
                if gc in [chr(27)]:
                    url = ""
                    break
            printn(k, chr(10) + url)
        geturl = arrcurl(url)
        geturl = gopherparse(k, geturl)
        for each in geturl:
            eachf = 1
            for redact in filters:
                if redact.lower() in each.lower():
                    eachf = 0
            if eachf == 1:
                if sq:
                    if sq.lower() in each.lower():
                         printn(k, each)
                else:
                    printn(k, each)
                    try: outfile.write(each + chr(10))
                    except: pass
        if qn: quit()
        try: outfile.write("") ; quit()
        except: pass

cur.wrapper(thee)
